//
//  LQOAuthViewController.swift
//  Weibo
//
//  Created by ios on 16/8/9.
//  Copyright © 2016年 ios. All rights reserved.
//

import UIKit
import SVProgressHUD
//  微博AppKey
let WeiboAppKey = "3489728523"
//  微博AppSecret
let WeiboAppSecret = "86c6097daf5e76449bebfff11914d4da"
//  授权回调页
let WeiboRedirect_Uri = "http://www.itcast.cn"
class LQOAuthViewController: UIViewController {
    
    private lazy var webView:UIWebView = UIWebView()
    override func loadView() {
        webView.opaque = false
        webView.delegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
      setnavUI()
      requestOAuthLogin()
            }
    
   private func setnavUI(){
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
     navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
    }
    
  @objc private  func cancelAction(){
    SVProgressHUD.dismiss()
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    
  @objc private func autoFillAction(){
    
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '15971504654';document.getElementById('passwd').value = 'qxy2682735'")
    

    
    }
    
    //MARK: --请求第三方登录页面
   private func requestOAuthLogin(){
    
    let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
    
    let urlRequest = NSURLRequest(URL: NSURL(string: url)!)
    
    webView.loadRequest(urlRequest)
    
    }
    
//    
//  //  通过code获取accesstoken
//    func reqeustAccessTokenWithCode(code: String){
//    LQAFNetworkingTools.sharedTools.reqeustAccessTokenWithCode(code) { (response, error) -> () in
//        if error != nil {
//            print("网络请求失败")
//            return
//        }
//      //  判断服务端给的数据是否是一个正确的字典  
//        guard let dic = response as? [String: AnyObject] else{
//          print("不是一个正确的字典格式")
//          return
//        }
//        //  代码执行到此,字典没有问题
//        let userAccount = LQUserAccount(dic: dic)
//        print(userAccount.access_token)
//        self.requestUserInfo(userAccount)
//    }
//}
//    
//    //  通过accesstoken和uid获取用户信息
//    func requestUserInfo(userAccount:LQUserAccount){
//    LQAFNetworkingTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
//        if error != nil {
//            print("网络请求失败")
//            return
//        }
//        guard let dic = response as? [String: AnyObject] else{
//            print("不是一个正确的字典格式")
//            return
//        }
//        let name = dic["name"]
//        let avatar_large = dic["avatar_large"]
//        userAccount.name = name as? String
//        userAccount.avatar_large = avatar_large as? String
//        
//        //保存用户信息
//        userAccount.saveUserAccount()
//        }
//    
//    }
}
//MARK: --UIWebViewDelegate 代理
extension LQOAuthViewController: UIWebViewDelegate{
    //  将要加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.URL else {
            return false
        }
        //  代码执行到此,url一定有值
        
        //  不是以回调页打头, 我不需要关心
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }
        //  代码执行到此,是我们的回调页打头
        
        if let query = url.query where query.hasPrefix("code=") {
            //  获取code
            print(query)
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
//              获取accesstoken
//            reqeustAccessTokenWithCode(code)
            LQUserAccountViewModel.shareUserAccount.reqeustAccessTokenWithCode(code, callBack: { (isSuccess) -> () in
                if isSuccess {
                print("登录成功")
                self.dismissViewControllerAnimated(true, completion: { () -> Void in
                    //发送通知切换跟控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                })
               
                }else{
                print("登录失败")
                }
            })
            
        }else{
            
          dismissViewControllerAnimated(true, completion: nil)
            
        }
        return false
    }
    //  开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }
    //  加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}